package com.ai.service.security.impl;

import com.ai.common.CommonResponse;
import com.ai.entity.security.SysRequestPath;
import com.ai.mapper.security.SysRequestPathMapper;
import com.ai.model.param.SysRequestPathParam;
import com.ai.service.security.ISysRequestPathService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 请求路径 服务实现类
 * </p>
 *
 * @author chen
 * @since 2023-04-04 19:46:06
 */
@Service
public class SysRequestPathServiceImpl extends ServiceImpl<SysRequestPathMapper, SysRequestPath> implements ISysRequestPathService {

    /**
     * 新增请求路径
     * @param requestPathParam
     * @return
     */
    @Override
    public CommonResponse<String> add(SysRequestPathParam requestPathParam) {

        //检测路径是否重复追加
        List<SysRequestPath> sysRequestPaths = this.list();

        List<String> urlList =
                sysRequestPaths.stream().map(SysRequestPath::getUrl).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(urlList) && urlList.contains(requestPathParam.getUrl())){
            return CommonResponse.error("当前路径已存在，请勿重复添加");
        }
        SysRequestPath sysRequestPath = new SysRequestPath();
        sysRequestPath.setUrl(requestPathParam.getUrl());
        sysRequestPath.setDescription(requestPathParam.getDescription());
        this.save(sysRequestPath);
        return CommonResponse.ok("新增成功");
    }

    /**
     * 更新请求路径
     * @param requestPathParam
     * @return
     */
    @Override
    public CommonResponse<String> updateSysRequestPath(SysRequestPathParam requestPathParam) {
        //检测路径是否重复追加
        List<SysRequestPath> sysRequestPaths = this.list();

        List<String> urlList =
                sysRequestPaths.stream().filter(sysRequestPath -> {
                    return (!(requestPathParam.getId().equals(sysRequestPath.getId().toString())));
                }).map(SysRequestPath::getUrl).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(urlList) && urlList.contains(requestPathParam.getUrl())){
            return CommonResponse.error("当前路径已存在，请勿重复添加");
        }

        SysRequestPath sysRequestPath = new SysRequestPath();
        sysRequestPath.setId(Integer.valueOf(requestPathParam.getId()));
        sysRequestPath.setUrl(requestPathParam.getUrl());
        sysRequestPath.setDescription(requestPathParam.getDescription());
        boolean b = this.updateById(sysRequestPath);
        if (b){
            return CommonResponse.ok("更新成功");
        }else {
            return CommonResponse.error("更新失败");
        }
    }

}
